package com.zy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zy.bean.po.Node;
import com.zy.mapper.NodeMapper;
import com.zy.parser.logicflow.LfNode;
import com.zy.service.NodeService;
import com.zy.util.UserUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author hanhuafeng
 * @createDate 2023-05-31 15:37:36
 * @description 流程图节点
 */
@Service
@RequiredArgsConstructor
public class NodeServiceImpl extends ServiceImpl<NodeMapper, Node>
        implements NodeService {
    private final UserUtil userUtil;

    /**
     * 更新流程图节点
     *
     * @param updateNode  更新的节点
     * @param chartCode   流程图编码
     * @param versionCode 版本编码
     */
    @Override
    public void updateNodeByLfNode(List<LfNode> updateNode, String chartCode, String versionCode) throws JsonProcessingException {
        ObjectMapper om = new ObjectMapper();
        for (LfNode node : updateNode) {
            Node n = new Node();
            n.setNodeId(node.getId());
            n.setY(node.getY());
            n.setX(node.getX());
            n.setType(node.getType());
            n.setProperties(om.writeValueAsString(node.getProperties()));
            n.setShowText(om.writeValueAsString(node.getText()));
            n.setChartCode(chartCode);
            n.setChartVersionCode(versionCode);
            n.setCreateUserId(userUtil.getUserCode());
            LambdaQueryWrapper<Node> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Node::getNodeId, node.getId());
            lqw.eq(Node::getChartCode, chartCode);
            lqw.eq(Node::getChartVersionCode, versionCode);
            this.update(n, lqw);
        }
    }

    /**
     * 复制节点
     *
     * @param chartCode      流程图编码
     * @param oldVersionCode 旧版本编码
     * @param versionCode    新版本编码
     */
    @Override
    public void copyNode(String chartCode, String oldVersionCode, String versionCode) {
        LambdaQueryWrapper<Node> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Node::getChartCode, chartCode);
        lqw.eq(Node::getChartVersionCode, oldVersionCode);
        List<Node> nodes = this.list(lqw);
        for (Node node : nodes) {
            node.setId(null);
            node.setChartVersionCode(versionCode);
            node.setCreateTime(null);
            node.setUpdateTime(null);
            node.setCreateUserId(userUtil.getUserCode());
            this.save(node);
        }
    }
}




